import os
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from models.Messages import *
from models.Topics import *
from models.Groups import *
from models.Users import *
from models.Audit import *
from models.Authentication import *
from datetime import *

class ViewMessage(webapp.RequestHandler):
    def get(self,messageID):
        user = get_current_user(self.request)
        if not user:
          return self.redirect("/login")
        
        if(int(messageID) not in user.readMessages):
            user.readMessages.append(int(messageID))
            user.put()

        message = Message.get_by_id(int(messageID))

        replies = []
        if(message):
            replies = Message.all()
            replies.filter("parent_id =",message.key().id())

        topic = Topic.get_by_id(message.topic)
        group = Group.get_by_id(topic.group_id)
        
        # check to see if the user is a moderator
        moderator = user.moderator

        path=os.path.join(os.path.dirname(__file__),"../templates/viewmessage.html")
        template_values = {"message":message,"replies":replies,"topic":topic,"group":group, "moderator":moderator}
        self.response.out.write(template.render(path,template_values))





class ViewMessagesByTopic(webapp.RequestHandler):
    def get(self,topicID):
        user = get_current_user(self.request)

        messages = Message.all()
        messages.filter("topic =",int(topicID))

        replies = []
        messagesWithCount = []
        mAuthor = None
        
        for message in messages:
          important = False;
          read = False;
          replies = Message.all()
          replies.filter("parent_id = ", message.key().id())
          count = replies.count()
          mAuthor = User.get_by_id(message.author)
          #mAuthor = message.author
          if(message.key().id() in user.importantMessages):
            important = True;
          if(message.key().id() in user.readMessages):
            read = True;
          messagesWithCount.append({"message":message, "count":count, "important":important,"read":read,"author":mAuthor})
          
        topic = Topic.get_by_id(int(topicID))
        group = Group.get_by_id(topic.group_id)


        template_values = {"messages":messagesWithCount,"topic":topic,"group":group}
        path=os.path.join(os.path.dirname(__file__),"../templates/viewmessagesbytopic.html")
        self.response.out.write(template.render(path,template_values))


class NewReply(webapp.RequestHandler):
  def get(self,parentID):
    template_values = {"messageForm" : ReplyMessageForm(),"parentID":parentID}
    path= os.path.join(os.path.dirname(__file__), "../templates/newreply.html")
    self.response.out.write(template.render(path, template_values))
  def post(self,parentID):
    user = get_current_user(self.request)

    data = ReplyMessageForm(data=self.request.POST)
    if(data.is_valid()):
      entity = data.save(commit=False)
      entity.parent_id = int(parentID)
      entity.subject = ""
      entity.author = user.key().id()
      entity.put()
      message = Message.get_by_id(int(parentID))
      self.redirect('/message/'+str(message.key().id()))
    else:
      template_values = {"messageForm" : data}
      path= os.path.join(os.path.dirname(__file__), "../templates/newreply.html")
      self.response.out.write(template.render(path, template_values))

       
class NewMessage(webapp.RequestHandler):
  def get(self,topicID):
    """Responds to get requests to the controller"""
    template_values = {"messageForm" : MessageForm(),"topicID":topicID}
    path= os.path.join(os.path.dirname(__file__), "../templates/newmessage.html")
    self.response.out.write(template.render(path, template_values))
  def post(self,topicID):
    data = MessageForm(data=self.request.POST)
    if(data.is_valid()):
      user = get_current_user(self.request)
      entity = data.save(commit=False)
      entity.topic = int(topicID)
      entity.author = user.key().id()
      entity.put()
      self.redirect('/topic/'+topicID)
    else:
      template_values = {"messageForm" : data,"topicID":topicID}
      path= os.path.join(os.path.dirname(__file__), "../templates/newmessage.html")
      self.response.out.write(template.render(path, template_values))


class DeleteMessage(webapp.RequestHandler):
    def get(self,messageID):
        message = Message.get_by_id(int(messageID))
        topicID = message.topic
        
        user = get_current_user(self.request)

        audit = Audit(
            ip = self.request.remote_addr,
            action = "Delete Message",
            date = datetime.now(),
            userID = user.key().id(),
            objectID = message.key().id() 
        )
        audit.setMessage()
        audit.put()

        message.delete()
        self.redirect('/topic/'+str(topicID));

"""------------------------------------------------------------------------
ModifyMessage
------------------------------------------------------------------------"""
class ModifyMessage(webapp.RequestHandler):
    def get(self,messageID):
        message = Message.get_by_id(int(messageID))

        template_values = {"message":message}
        path = os.path.join(os.path.dirname(__file__),"../templates/ModifyMessage.html")
        self.response.out.write(template.render(path,template_values))
    def post(self,messageID):
        message = Message.get_by_id(int(messageID))

        user = get_current_user(self.request)

        audit = Audit(
            ip = self.request.remote_addr,
            action = "Modify Message (Changed message to: "+self.request.get('message')[:10]+ "...)",
            date = datetime.now(),
            userID = user.key().id(),
            objectID = message.key().id() 
        )
        audit.setMessage()
        audit.put()

        message.subject = self.request.get('subject')
        message.message = self.request.get('message')
        message.put()
        self.redirect('/message/'+str(message.key().id()))
        



class ModifyImportant(webapp.RequestHandler):
    def get(self,messageID):
        user = get_current_user(self.request)
        if(int(messageID) in user.importantMessages):
            user.importantMessages.remove(int(messageID))
            user.put()
        else:
            user.importantMessages.append(int(messageID))
            user.put()

        self.response.out.write("Success")

class ModifyRead(webapp.RequestHandler):
    def get(self,readunread,messageID):
        user = get_current_user(self.request)

        if(int(readunread)==1):
            if(int(messageID) in user.readMessages):
                return
            else:
                user.readMessages.append(int(messageID))
                user.put()
        else:
            if(int(messageID) in user.readMessages):
                user.readMessages.remove(int(messageID))
                user.put()
            else:
                return

            
